import router from '@/router'
import store from '@/store'
import Nprogress from 'nprogress'
import 'nprogress/nprogress.css'
import { cancelAll } from './utils/request'

const whitePage = ['/404', '/login']

router.beforeEach(async(to, from, next) => {
  Nprogress.start()
  if (store.state.user.token) {
    // 如果进入的登录页面但是有token,就跳转到首页
    if (to.path.toLowerCase() === '/login') {
      next('/')
    } else {
      if (store.state.user.userInfo.userId) {
        next()
      } else {
        await store.dispatch('user/getUserInfo')
        next(to.fullPath)
      }
      // next()
    }
  } else {
    // 如果没有token且跳转的是白名单中的页面,则放行
    if (whitePage.includes(to.path.toLowerCase())) {
      next()
    } else {
      next('/login?redirect=' + to.fullPath)
    }
  }
  Nprogress.done()
})

router.afterEach((to, from) => {
  cancelAll()
  Nprogress.done()
})
